<template>
  <div class="app-container">
    <el-form ref="authForm" :model="form" v-if="open" :rules="rules" label-width="100px">
      <!-- 合作商类型选择 -->
      <div class="partner-type">
        <el-radio-group v-model="form.partnerType" @change="handlePartnerTypeChange">
          <el-radio label="strategic">战略合作商</el-radio>
          <el-radio label="guarantee">担保合作商</el-radio>
        </el-radio-group>
      </div>

      <!-- 普通认证表单项 -->
      <div class="form-content">
        <el-form-item label="公司名称" prop="companyName">
          <el-input
            v-model="form.companyName"
            :placeholder="companyNamePlaceholder"
            clearable
            style="width: 300px"
          />
        </el-form-item>

        <el-form-item label="营业执照" prop="businessLicense">
          <file-upload
            v-model="form.businessLicense"
            :limit="1"
            accept=".jpg,.png,.pdf"
            tip="请上传营业执照扫描件"
          />
        </el-form-item>

        <el-form-item label="注册信息" prop="registration">
          <file-upload
            v-model="form.registration"
            :limit="1"
            accept=".jpg,.png,.pdf"
            tip="请上传注册信息文件"
          />
        </el-form-item>

        <el-form-item label="电子合同" prop="contract">
          <file-upload
            v-model="form.contract"
            :limit="1"
            accept=".pdf,.doc,.docx"
            tip="请上传电子合同文件"
          />
        </el-form-item>
      </div>

      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">提交认证</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-form>
    <!-- 信息提交后状态 -->
    <el-form ref="authForm" :model="formData" v-else  label-width="100px">

      <!-- 普通认证表单项 -->
      <div>
        <el-form-item label="公司名称" prop="companyName">
          <el-input
            v-model="formData.companyName"
            :readonly="true"
            style="width: 300px"
          />
        </el-form-item>

        <el-form-item label="营业执照" prop="businessLicense">
          <el-button @click="downloadFile(formData.businessLicense)">文件下载</el-button>
        </el-form-item>

        <el-form-item label="注册信息" prop="registration">
          <el-button @click="downloadFile(formData.registration)">文件下载</el-button>
        </el-form-item>

        <el-form-item label="电子合同" prop="contract">
          <el-button @click="downloadFile(formData.contract)">文件下载</el-button>
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-tag :type="getStatusType(formData.status)" disable-transitions>{{ getStatusText(formData.status) }}</el-tag>
        </el-form-item>

        <div class="dialog-footer" v-if="formData.status==='2'">
          <el-button type="primary" @click="update">修改</el-button>
        </div>
      </div>
    </el-form>

  </div>
</template>

<script>
import { listPurch_info,  updatePurch_info,authPurch_info } from "@/api/system/purch_info";
import { getUserProfile } from "@/api/system/user";
import request from '@/utils/request'
import {updateSupInfo} from "@/api/supply/supInfoUpdate";

export default {
  name: "PurchaserAuth",
  inject: ['globalData'],
  data() {
    return {
      title: "采购商认证",
      open: true,
      isUpdate: false,
      companyNamePlaceholder: "请输入公司全称",
      form: {
        partnerType: 'strategic', // 默认为战略合作商
        companyName: null,
        businessLicense: null,
        registration: null,
        contract: null
      },
      formData:{},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        purchaserId: null,
        companyName: null,
        businessLicense: null,
        registration: null,
        contract: null,
        createdAt: null,
        updatedAt: null,
        status: null,
        auditorId: null
      },

      rules: {
        partnerType: [
          {
            required: true,
            message: "请选择合作商类型",
            trigger: "change"
          }
        ],
        companyName: [
          {
            required: true,
            message: "请输入公司名称",
            trigger: "blur"
          }
        ],
        businessLicense: [
          {
            required: true,
            message: "请上传营业执照",
            trigger: "change"
          }
        ],
        registration: [
          {
            required: true,
            message: "请上传注册信息",
            trigger: "change"
          }
        ],
        contract: [
          {
            required: true,
            message: "请上传电子合同",
            trigger: "change"
          }
        ]
      }
    };
  },
  created() {
    this.checkAuth();
  },
  methods: {
    checkAuth() {
      getUserProfile().then(response => {
        this.queryParams.purchaserId=response.data.userId;
        listPurch_info(this.queryParams).then(response => {
          if(response.rows.length!=0){
            this.open=false;
            this.formData=response.rows[0];
            // this.formData.businessLicense='https://view.officeapps.live.com/op/view.aspx?src='+this.formData.businessLicense;
            // this.formData.registration='https://view.officeapps.live.com/op/view.aspx?src='+this.formData.registration;
            // this.formData.contract='https://view.officeapps.live.com/op/view.aspx?src='+this.formData.contract;
          }
        });
      });
    },

    // 提交表单
    submitForm() {
      this.$refs.authForm.validate(valid => {
        if (valid) {
          // 检查文件是否已上传成功
          if (!this.form.businessLicense) {
            this.$modal.msgWarning("请上传营业执照");
            return;
          }
          if (!this.form.registration) {
            this.$modal.msgWarning("请上传注册信息");
            return;
          }
          if (!this.form.contract) {
            this.$modal.msgWarning("请上传电子合同");
            return;
          }

          // 显示加载中提示
          this.$modal.loading("数据提交中，文件上传可能需要一些时间，请耐心等待...");

          // 构建提交数据 - 按照后端实体类SupInfoUpdate的字段名进行调整
          const submitData = {
            // 保持公司名称
            companyName: this.form.companyName,
            // 根据后端实体类的字段名和JsonProperty注解调整
            file1: this.form.businessLicense, // 对应@JsonProperty("businessLicense")
            file2: this.form.registration,    // 对应@JsonProperty("registration")
            contract: this.form.contract,     // 合同文件
            partnerType: this.form.partnerType // 合作商类型
          };

          console.log("准备发送数据：", submitData);

          // 使用封装的API函数发送请求
          updateSupInfo(submitData)
            .then(res => {
              // 关闭加载提示
              this.$modal.closeLoading();

              if (res.code === 200) {
                // 成功提示
                this.$modal.msgSuccess("提交成功！您的供应商资质认证信息已提交");
                location.reload();
              } else {
                // 使用后端返回的错误消息
                this.$modal.msgError(res.msg || "提交失败，请检查数据后重试");
              }
            }).catch(error => {
              // 关闭加载提示
              this.$modal.closeLoading();

              // 显示错误信息
              this.$modal.msgError("提交失败：" + (error.message || "服务器连接异常，请稍后再试"));
              console.error("数据提交错误:", error);
            });
        } else {
          this.$modal.msgWarning("表单验证未通过，请检查并修正红色提示项");
          return false;
        }
      });
    },
    //修改表单
    update() {
      this.open = true;
      this.isUpdate = true;
    },
    cancel() {
      this.resetForm()
    },

    resetForm() {
      this.form = {
        partnerType: 'strategic',
        companyName: "",
        businessLicense: null,
        registration: null,
        contract: null
      }
      this.$refs.authForm.resetFields()
    },
    getStatusText(status) {
      switch (status) {
        case '0':
          return '未审核';
        case '1':
          return '审核通过';
        case '2':
          return '审核未通过';
        default:
          return '未知状态';
      }
    },
    getStatusType(status) {
      switch (status) {
        case '0':
          return 'info'; // 蓝色
        case '1':
          return 'success'; // 绿色
        case '2':
          return 'danger'; // 红色
        default:
          return '';
      }
    },
    downloadFile(src) {
      var elemIF = document.createElement('iframe');
      elemIF.src = src;
      elemIF.style.display = 'none';
      document.body.appendChild(elemIF);
    },
    handlePartnerTypeChange(value) {
      if (value === 'strategic') {
        this.companyNamePlaceholder = "请输入您的公司名称";
      } else if (value === 'guarantee') {
        this.companyNamePlaceholder = "请输入担保公司名称";
      }
    }
  }
};
</script>

<style scoped>
.partner-type {
  margin-bottom: 30px;
}

.form-content {
  margin-top: 20px;
}
</style>
